package com.unhz.taigu.controller;

import com.unhz.generator.dao.UserMapper;
import com.unhz.generator.pojo.LoginInfo;
import com.unhz.generator.pojo.ProductionRange;
import com.unhz.generator.pojo.User;
import com.unhz.generator.utils.*;
import com.unhz.taigu.service.AreaDictService;
import com.unhz.taigu.service.LoginInfoService;
import com.unhz.taigu.service.ProductionRangeService;
import com.unhz.taigu.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * @Author: 沈佳庆
 * @Description:
 * @Date: Created in 下午 3:17 2018/3/12 0012
 * @Modified By: V1.0.0
 */
@Controller
@RequestMapping("login")
public class LongUserController {

    private final Logger logger = LoggerFactory.getLogger(LoginInfo.class);
    @Autowired
    private UserService userService;
    @Autowired
    private LoginInfoService loginInfoService;
    @Autowired
    private ProductionRangeService productionRangeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AreaDictService areaDictService;

    @RequestMapping("login")
    @ResponseBody
    public JsonResult findLongUser(@RequestParam("userPhone") String userPhone,
                                   @RequestParam("userPassword") String userPassword, HttpSession session) {
        User user = userService.findUserPhone(userPhone);
        if (user != null) {
            User u = userService.findLongUser(userPhone, MD5.MD5Encode(userPassword));
            if (u != null) {
                session.setAttribute("user", u);
                logger.info("登录的时间：" + new Date() + " ---登录用户：" + u.getUserPhone());
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUserId(u.getId());//登录id
                loginInfo.setLoginTime(new Date());//登录时间
                loginInfo.setUser(u);//user
                int count = loginInfoService.insertLoginInfo(loginInfo);
                return JsonResult.success("1", u);//1 表示成功
            }
            return JsonResult.failure("2");////2 表示密码错误
        }
        return JsonResult.failure("3");////3 手机号错误
    }


    /**
     * 添加个人资料（挡板）
     *
     * @return
     */
 /*   @RequestMapping("/insert")
    @ResponseBody
    public JsonResult insert(User user,String[] production) {
        ProductionRange produc = new ProductionRange();
            //添加

            user.setValid(1);
            int flag = userMapper.insertSelective(user);
            if (flag > 0) {
                for (int i = 0; i < production.length; i++) {
                    produc.setUserId(user.getId());
                    produc.setProductionRange(production[i]);
                    produc.setCreateTime(new Date());
                    productionRangeService.insert(produc);
                }
                return JsonResult.success("添加成功", flag);
            }

        return JsonResult.failure("添加失败");
    }*/

    /**
     * 修改个人资料
     *
     * @param user
     * @param userId
     * @param production
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public JsonResult updateUser(User user, String userId, String[] production) {
        ProductionRange produc = new ProductionRange();
        user.setId(Integer.parseInt(userId));
             /*修改*/
        user.setValid(1);
        int xin = userMapper.updateByPrimaryKeySelective(user);

        if (xin > 0) {
            //先删除之前的生产范围
            productionRangeService.deleteByUserId(Integer.parseInt(userId));
            for (int i = 0; i < production.length; i++) {
                produc.setUserId(Integer.parseInt(userId));
                produc.setProductionRange(production[i]);
                produc.setCreateTime(new Date());
                productionRangeService.insert(produc);
            }
            return JsonResult.success("修改成功", xin);
        }
        return JsonResult.failure("修改失败");
    }

    /**
     * 重置密码
     */
    @RequestMapping("updateLoginPassword")
    @ResponseBody
    public JsonResult updateLoginPassword(@RequestParam(value = "userId") String userId, @RequestParam(value = "userPassword") String userPassword,
                                          @RequestParam(value = "userPassword2") String userPassword2) {
        User ures = userService.selectById(Integer.parseInt(userId));
        Map<String, String> smsInf = SmsUtil.getSmsCode(ures.getUserPhone());
        if (smsInf != null) {
            if (userPassword.equals(userPassword2)) {
                //修改密码
                int j = userMapper.updateLoginPassword(Integer.parseInt(userId), MD5.MD5Encode(userPassword));
                return JsonResult.success("0", j);//修改成功
            }
            return JsonResult.failure("1");//修改失败
        }
        return JsonResult.failure("2");//请用旧手机重新验证
    }


    /**
     * 注册
     * @param userPhone     手机号
     * @param userPassword  密码
     * @param userPassword2 确认密码
     * @param phoneCode   手机验证码
     * @return
     * @throws IOException
     */
    @RequestMapping("register")
    @ResponseBody
    public JsonResult Verificode(@RequestParam(value = "userPhone") String userPhone,
                                 @RequestParam(value = "userPassword", required = false) String userPassword,
                                 @RequestParam(value = "userPassword2", required = false) String userPassword2,
                                 @RequestParam(value = "phoneCode",required=false) String phoneCode) throws IOException {
        User user = new User();
        User u = userService.findUserPhone(userPhone);
        if (u == null) {
            Map<String, String> smsInfo = SmsUtil.getSmsCode(userPhone);
        /*判断重复密码*/
            if (userPassword.equals(userPassword2)) {
                //手机验证码
                if (smsInfo != null) {
                    String smsCode = smsInfo.get("smsCode");
                    Long expries = Long.valueOf(smsInfo.get("expries"));
                    if (new Date().getTime() - expries < 5 * 60 * 1000) {
                        if (phoneCode.equals(smsCode)) {
                            //获取用户输入的验证码
                                user.setUserPhone(userPhone);
                                user.setUserPassword(MD5.MD5Encode(userPassword));
                                user.setCreateTime(new Date());
                                user.setValid(1);
                                user.setSource(0);
                                userService.insert(user);
                                return JsonResult.success("0", user.getId());//注册成功
                        }
                        SmsUtil.removeSmsCode(userPhone);
                        return JsonResult.failure("1");//短信验证码错误
                    }
                    SmsUtil.removeSmsCode(userPhone);
                    return JsonResult.failure("2");//短信验证码超时
                }
                    return JsonResult.failure("3");//短信验证码超时
            }
            return JsonResult.failure("4");//重复密码错误
        }
        return JsonResult.failure("5");//手机号已存在
    }


    /**
     * 图片验证码
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("getImgCode")
    @ResponseBody
    public JsonResult getImgCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VerifiCode v = new VerifiCode();     //用我们的验证码类，生成验证码类对象
        BufferedImage image = v.getImage();  //获取验证码
        request.getSession().setAttribute("text", v.getText()); //将验证码的文本存在session中
        v.output(image, response.getOutputStream());//将验证码图片响应给客户端
        return JsonResult.success("image", response.getOutputStream());
    }


    /**
     * 验证图片验证码
     * @param code
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("verifyImgCode")
    @ResponseBody
    public JsonResult verifyImgCode(@RequestParam(value = "code",required = false) String code,HttpServletRequest request,HttpSession session)
    {
        String session_vcode = (String) request.getSession().getAttribute("text");
        System.out.println(session_vcode.toLowerCase()+"----------------"+code.toLowerCase());
        if (session_vcode.toLowerCase().equals(code.toLowerCase()))
        {
            return JsonResult.success("0"); //验证成功
        }
        return JsonResult.failure("1");//验证失败
    }



    /**
     * 发送验证码
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping("/findphonecode")
    @ResponseBody
    public JsonResult findphonecode(@RequestParam(required = false) String phone,HttpServletRequest request) throws Exception {
        MsgUtil msg = new MsgUtil();
        User u = userService.findUserPhone(phone);
        if (u == null) {

            Map map = msg.sendMsg(phone, request);
            if (map != null) {
                return JsonResult.success("0", map);//0 验证码获取成功
            }
            return JsonResult.failure("1");//短信验证码错误
        }
        return JsonResult.failure("2");//手机号已存在
    }


    /**
     * 发送验证码
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping("/phonecode")
    @ResponseBody
    public JsonResult phonecode(@RequestParam(required = false) String phone,HttpServletRequest request) throws Exception {
        MsgUtil msg = new MsgUtil();
        User u = userService.findUserPhone(phone);
        if (u != null) {
            Map map = msg.sendMsg(phone, request);
            if (map != null) {
                return JsonResult.success("0", map);//验证码获取成功
            }
            return JsonResult.failure("1");//短信验证码错误
        }
        return JsonResult.failure("2");//手机号不存在
    }

    /**
     * 验证身份
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping("verifyPhone")
    @ResponseBody
    public JsonResult verifyPhone(@RequestParam(value = "phone", required = false) String phone,
                                  @RequestParam(value = "code", required = false) String code,
                                   HttpServletRequest request) {
        Map<String, String> smsInfo = SmsUtil.getSmsCode(phone);
        String session_vcode = (String) request.getSession().getAttribute("text");
        //判断验证
        User u = userService.findUserPhone(phone);
        if (u != null) {
            if (smsInfo != null) {
                String smsCode = smsInfo.get("smsCode");
                Long expries = Long.valueOf(smsInfo.get("expries"));
                if (new Date().getTime() - expries < 1 * 60 * 1000) {
                    if (code.equals(smsCode)) {
                          List info=new ArrayList();
                          info.add(u.getId());
                          info.add(u.getUserPhone());
                          info.add(u.getUserName());
                          return JsonResult.success("0",info);//身份验证成功
                    }
                    return JsonResult.failure("1");//短信验证码错误
                }
                SmsUtil.removeSmsCode(phone);
                return JsonResult.failure("2");//短信验证码超时
            }
            SmsUtil.removeSmsCode(phone);
            return JsonResult.failure("3");//短信验证码超时
        }
        return JsonResult.failure("4");//手机号不存在
    }



    /**
     * 修改发送验证码
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping("/updatePhoneCode")
    @ResponseBody
    public JsonResult updatphonecode(@RequestParam(required = false) String phone,HttpServletRequest request) throws Exception {
        MsgUtil msg = new MsgUtil();
        User u = userService.findUserPhone(phone);
        if (u == null) {
            Map map = msg.sendMsg(phone, request);
            if (map != null) {
                return JsonResult.success("0", map);//验证码获取成功
            }
            return JsonResult.failure("1");//短信验证码错误
        }
        return JsonResult.failure("2");//不能与旧手机号相同
    }

    /**
     *  更改手机号接口
     * @param phone
     * @param code
     * @param userid
     * @param request
     * @return
     */
    @RequestMapping("updatePhone")
    @ResponseBody
    public  JsonResult updatePhone(@RequestParam(value = "phone",required = false) String phone,
                                   @RequestParam(value = "code",required= false) String code,
                                   @RequestParam(value = "userid",required= false) int userid,
                                   HttpServletRequest request) {

        User ures = userService.selectById(userid);
        Map<String, String> smsInf = SmsUtil.getSmsCode(ures.getUserPhone());
        if (smsInf != null) {
            User u = userService.findUserPhone(phone);
            if (u == null) {
                Map<String, String> smsInfo = SmsUtil.getSmsCode(phone);
                //判断验证
                if (smsInfo != null) {
                    String smsCode = smsInfo.get("smsCode");
                    Long expries = Long.valueOf(smsInfo.get("expries"));
                    if (new Date().getTime() - expries < 5 * 60 * 1000) {
                        if (!code.equals(smsCode)) {
                            return JsonResult.failure("5");//短信验证码错误
                        } else {
                            //验证码正确，注册成功
                            User user = new User();
                            user.setUserPhone(phone);
                            user.setId(userid);
                            userService.updatePhone(user);

                            SmsUtil.removeSmsCode(ures.getUserPhone());
                            return JsonResult.success("0");//修改成功

                        }
                    } else {
                        SmsUtil.removeSmsCode(phone);
                        return JsonResult.failure("1");//短信验证码超时
                    }
                }
                SmsUtil.removeSmsCode(phone);
                return JsonResult.failure("2");//短信验证码超时
            }
            return JsonResult.failure("3");//手机号已存在
        }

        return JsonResult.failure("4");//请重新验证旧手机号
    }


    /**
     * 查询个人资料
     * @param userid
     * @return
     */
    @RequestMapping("personaldata")
    @ResponseBody
    public  JsonResult personaldata(@RequestParam(value = "userid",required = false) int userid) {
        Map map=new HashMap();
        List list=new ArrayList();
        User user = userService.selectByPrimaryKey(userid);
        List<ProductionRange> pro=    productionRangeService.selectByUserId(user.getId());
        list.add(user);
        list.add(pro);
        map.put("user",list);
        if (user != null)
        {
            map.put("areaDict",areaDictService.selectAreaDictAll());
            return JsonResult.success("0",map);//查询成功
        }
        return JsonResult.failure("1");//查询失败
    }


}
